package com.base.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.base.admin.context.GlobalContext;
import com.base.admin.entity.AdminUser;
import com.base.admin.service.AdminUserService;
import com.base.admin.util.DigestUtils;
import com.base.admin.vo.ResultBean;
import com.base.admin.vo.UpdatePasswordVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.xml.transform.Result;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author rqq
 */

@RestController
@RequiredArgsConstructor
public class IndexController {

    private final AdminUserService appAdminUserService;

    @PostMapping("/login")
    public ResultBean<String> login(@RequestBody @Valid AdminUser adminUser) {
        return ResultBean.success(appAdminUserService.login(adminUser.getUsername(), adminUser.getPassword()));
    }

    @GetMapping("/getUserInfo")
    public ResultBean<AdminUser> getLoginUserInfo() {
        return ResultBean.success(appAdminUserService.getLoginUserInfo());
    }

    @PostMapping("updatePassword")
    public ResultBean<Void> updatePassword(@RequestBody @Valid UpdatePasswordVO updatePasswordVO) {

        AdminUser loginUser = GlobalContext.getLoginUser();
        if (!loginUser.getPassword().equals(DigestUtils.sha256Encrypt(updatePasswordVO.getOldPassword()))) {
            return ResultBean.error("旧密码错误");
        }
        if (!updatePasswordVO.getConfirmPassword().equals(updatePasswordVO.getNewPassword())) {
            return ResultBean.error("两次输入密码不一致");
        }
        if (updatePasswordVO.getNewPassword().equals(updatePasswordVO.getOldPassword())) {
            return ResultBean.error("旧密码和新密码一致");
        }
        loginUser.setPassword(DigestUtils.sha256Encrypt(updatePasswordVO.getNewPassword()));
        loginUser.setUpdateTime(new Date());
        appAdminUserService.updateById(loginUser);
        return ResultBean.success();
    }
}
